package com.monolithiot.notifier.sms.impl;

import com.monolithiot.notifier.common.util.IdentityUtil;
import com.monolithiot.notifier.common.vo.VerifySms;
import com.monolithiot.notifier.context.Constant;
import com.monolithiot.notifier.sms.SmsSender;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.api.SmsApi;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 2018/12/22 Create by 郭文梁
 * YunPianSmsSenderAdapter
 * 云片API 断行发送适配器
 *
 * @author 郭文梁
 * @date 2018/12/22
 */
@Component
public class YunPianSmsSenderAdapter implements SmsSender {
    private SmsApi smsApi;

    @Autowired
    public YunPianSmsSenderAdapter(YunpianClient yunpianClient) {
        this.smsApi = yunpianClient.sms();
    }

    @Override
    public VerifySms sendVerificationCode(String mobileNumber) throws SendException {
        Map<String, String> param = new HashMap<>(3);
        String code = IdentityUtil.randomNumberCode(Constant.Sms.DEFAULT_VERIFICATION_CODE_LENGTH);
        String text = String.format(Constant.Sms.VERIFICATION_CODE_SMS_TEMPLATE, code);
        param.put("mobile", mobileNumber);
        param.put("text", text);
        Result<SmsSingleSend> sendResult = smsApi.single_send(param);
        if (sendResult.isSucc()) {
            VerifySms res = new VerifySms();
            res.setCode(code);
            res.setText(text);
            return res;
        }
        throw new SendException(String.format("Could send verification code [%s] to [%s]", code, mobileNumber));
    }
}
